#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <rtthread.h>
#include "rtdevice.h"

#define DBG_TAG "led.c"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>

#include "led.h"
#include "cJSON.h"

/*
 {
     "method":"control",
     "clientToken":"clientToken-QU69y3f-Z",
     "params":{
         "led2":0
     }
 }
 */
// 解析收到消息
void parse_msg(uint32_t msg_len, char *msg)
{
    if(msg_len == 0)
        return;

    cJSON *obj = cJSON_Parse(msg);
    if(obj == NULL)
        goto _err0;

    cJSON *method = cJSON_GetObjectItem(obj, "method");  // 在子节点中找到对应的键
    if(method == NULL)
        goto _err1;

    if(strncmp(method->valuestring, "control", 7) != 0)
        goto _err1;

    cJSON *params = cJSON_GetObjectItem(obj, "params");
    if(params == NULL)
        goto _err1;

    cJSON *led1 = cJSON_GetObjectItem(params, "led1");
    if(led1 != NULL)
    {
        if(led1->valueint == 0)
            led1_off();
        else if(led1->valueint == 1)
            led1_on();
    }

    cJSON *led2 = cJSON_GetObjectItem(params, "led2");
    if(led2 != NULL)
    {
        if(led2->valueint == 0)
            led2_off();
        else if(led2->valueint == 1)
            led2_on();
    }

    if(obj != NULL)
        cJSON_Delete(obj);  // 释放空间

    return;

_err1:
    if(obj != NULL)
        cJSON_Delete(obj);  // 释放空间
_err0:
    return;
}
